/**
 * Created by Administrator on 2015/1/25.
 */
var fs = require('fs');
var path = require('path');
var ejs = require('ejs');
var logger = require('./logger');
var config = require('./config');
var dateFormat = require('dateformat');
var xml2js = require('xml2js');
var Fiber = require('fibers');

var builder = new xml2js.Builder();  // JSON->xml
var parser = new xml2js.Parser({explicitArray: false, async: false});   //xml -> json

exports.processEjsTemplate = function (templateName, data) {
    var file = path.join(config.Config().templateDir, templateName + ".ejs");
    var ejsStr = fs.readFileSync(file, {encoding: "UTF-8"});
    logger.debug("ejs Template", ejsStr, {debug: true, escape: true});
    return ejs.render(ejsStr, data);
}


exports.getNowTimeStr = function () {
    var now = new Date();
    var timeStr = dateFormat(now, "yyyy-mm-dd HH:MM:ss");
    return timeStr;
}

exports.paraseXML = function (xmlParam) {
    var jsonParam = null;
    parser.parseString(xmlParam, function (err, result) {
        jsonParam = result.xml;
    });
    return jsonParam;
}


exports.splitCheck = function (text, length) {
    try {
        var temp = text.split("%");
        if (temp.length != length) {
            return 0;
        }
        for (var i = 0; i < temp.length; i++) {
            var word = temp[i].replace(/(^\s*)|(\s*$)/g, "");
            if (word == null || word == "") {
                return 0;
            }
        }
        return 1;
    } catch (e) {
        logger.error("split check error", e);
        return 0;
    }
}


exports.calcWordLength = function (str) {
    var real = str.replace(/[^\x00-\xff]/g, '_'); //这个把所有双字节变单字节
    return real.length;
}

//四位数字与字母
var chars = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
var gameIdlength = 4;
exports.generateGameID = function () {
    logger.debug("char length", chars.length);
    var res = "";
    for (var i = 0; i < gameIdlength; i++) {
        var id = Math.ceil(Math.random() * (chars.length - 1));
        res += chars[id];
    }
    return res;
}

var protocols = {
    http: require('http'),
    https: require('https')
};

exports.syncHttpGet = function (url) {
    logger.info("syncHttpGet url", url);
    var protocol = url.substring(0, url.indexOf("://"));
    var fiber;
    fiber = Fiber.current;
    var result = null;
    protocols[protocol].get(url, function (res) {
        var data = ""
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            result = data;
            if (fiber) {
                fiber.run(result);
            }
        });
    });
    Fiber.yield();
    return  result;
}